package com.effective.java.clone;

public class CloneElements01 implements Cloneable {

	private Element[] elements;

	public static void main(String[] args) {

		CloneElements01 instance1 = new CloneElements01();
		instance1.elements[0] = new Element(3);
		instance1.elements[1] = new Element(5);
		CloneElements01 instance2 = instance1.clone();

		System.out.println(instance1);
		System.out.println(instance2);

		instance1.elements[0].setI(7);

		System.out.println(instance1);
		System.out.println(instance2);
	}

	public CloneElements01() {

		this.elements = new Element[5];
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public CloneElements01 clone() {

		CloneElements01 clone = new CloneElements01();
		for (int i = 0; i < this.elements.length; i++) {

			Element e = this.elements[i];
			if (e != null) {
				clone.elements[i] = e.clone();
			}
		}
		return clone;
	}

	@Override
	public String toString() {

		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < this.elements.length; i++) {

			Element e = this.elements[i];
			if (e != null) {
				builder.append("[" + i + "  = " + e + " ]");
			}
		}
		return builder.toString();
	}

	private static class Element implements Cloneable {

		private Integer value;

		public Element(int i) {

			this.value = Integer.valueOf(i);
		}

		public void setI(Integer i) {
			this.value = i;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public String toString() {

			StringBuilder builder = new StringBuilder(super.toString());
			builder.append(" { value = '" + this.value + "' }");
			return builder.toString();
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public Element clone() {

			return new Element(this.value);
		}
	}
}
